package com.app.Activity;

import java.util.ArrayList;

import it.unipr.ce.dsg.s2p.sip.Address;

import com.app.Controller.NetworkController;
import com.app.Controller.ReadWriteFileController;
import com.app.DTO.AccountDTO;
import com.app.DTO.RoleDTO;

import ReadWriteXML.CMember;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;

import com.app.Network.PingThread;
import com.app.Network.Protocol;
import com.app.PhanQuyen.Quyen;
import com.app.Tree.BoardView;

import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import app.com.ModuleRole.R;

public class tabActivity extends TabActivity {

	public static int CODE_KICK = 101;
	public static int CODE_CHATPEER = 401;
	public static String IP_CHATPEER = "IP_CHATPEER";
	public static int CODE_CHAT = 201;
	public static int CODE_STOP_TALK = 301;
	public static String IP_RESULT = "IP_RESULT";

	private static TabHost _tabHost;
	// ==========================================
	public static String message;
	public static Runnable showMessage;
	public static int kickVoteResult;
	public static Address ipBeingKick;
	public static Address ipBeingStopTalk;
	public static int timeVoteKick;
	int timeStopTalk;
	ArrayList<CMember> memberList;
	public static ArrayList<Integer> yesVote;
	public static ArrayList<Integer> noVote;
	public static Runnable dislayKickMember;
	public static Runnable dislayKickedMessage;
	// =========================================

	private static Context _cont;
	private static int _tabIndex = 1;
	LocalActivityManager localActivity;
	PingThread t;
	private TabHost mTabHost;
	private Context mTabHostContext;
	private View surfaceView1, surfaceView2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_tab);
		memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
		localActivity = new LocalActivityManager(this, false);
		_cont = this;
		Resources res = getResources(); // Resource object to get Drawables
		
		TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost); // The
																		// activity
																		// TabHost
		TabHost.TabSpec spec; // Resusable TabSpec for each tab
		Intent intent; // Reusable Intent for each tab
		localActivity.dispatchCreate(savedInstanceState);
		tabHost.setup(localActivity);
		// Initialize a TabSpec for each tab and add it to the TabHost
		intent = new Intent().setClass(this, trucActivity.class);
		spec = tabHost.newTabSpec("subject").setIndicator("Học tập"
		// , res.getDrawable(R.drawable.ic_tab_subject)
				).setContent(intent);
		tabHost.addTab(spec);

		
		intent = new Intent(getBaseContext(), frmTreeNodeActivity.class);
		spec = tabHost.newTabSpec("treenode").setIndicator("Cây thảo luận");
		spec.setContent(intent);
		tabHost.addTab(spec);
		
		
//		intent = new Intent().setClass(this, frmTextNodeActivity.class);;
//		spec = tabHost.newTabSpec("textnode").setIndicator("Thảo luận");
//		spec.setContent(intent);
//		tabHost.addTab(spec);

//		setupTabHost(); //Prepares the TabHost from code rather than XML;
//	    //mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider); //Sets a thin dividing line
//	    mTabHostContext = mTabHost.getContext();
//	    surfaceView1 = LayoutInflater.from(mTabHostContext).inflate(R.layout.layout_surfaceview_treenode, null);
//	    BoardView s = (BoardView)surfaceView1.findViewById(R.id.boardviewtree);
//	    /*
//	     * Change the colour to red
//	     */
//	   // s.changeColour(getResources().getColor(R.color.red_square));
//
//	    /*
//	     * Create a second layout containing SurfaceViewCircle but leave circle as default blue.
//	     */
//	    surfaceView2 = LayoutInflater.from(mTabHostContext).inflate(R.layout.layout_surfaceview_textnode, null);
//	    setupTab(surfaceView1,"SurfaceView1");
//	    setupTab(surfaceView2,"SurfaceView2");
//
//
//	}
//
//	private void setupTabHost() {
//	    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
//	    mTabHost.setup();
//	}
//
//	private void setupTab(final View view, final String tag) {
//	    View tabview = createTabView(mTabHost.getContext(), tag); // This creates a view to be used in the TAB only
//
//	    /* this creates the tab content AND applies the TAB created in the previous step in one go */
//	    TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
//	        public View createTabContent(String tag) {return view;}
//	    });
//	    mTabHost.addTab(setContent);
//
//	}
//
//	private static View createTabView(final Context context, final String text) {
//	    View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
//	    TextView tv = (TextView) view.findViewById(R.id.tabsText);
//	    tv.setText(text);
//
//	    return view;
//	}   
		
		dislayKickMember = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HienThiMHBieuQuyetKick();
			}
		};

		dislayKickedMessage = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ShowMessageKicked();
			}
		};
		showMessage = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Show(message);
			}
		};

		// get_tabHost().getChildAt(0).setOnClickListener(new OnClickListener()
		// {
		// @Override
		// public void onClick(View v) {
		// getTabHost().setCurrentTab(0);
		// }
		// });
//		NetworkController.isConnected=true;
//		if(PingThread.getInstance(false).getState()==Thread.State.NEW){
//			PingThread.getInstance(false).start();
//			Log.d("Phu","start ping in tab");
//		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.d("PEERDROID", "vao onresume tab host");
		Log.d("PEERDROID", "tabIndex: " + _tabIndex);
		// frmTreeNodeActivity.board.isRunning=false;
		// switch (_tabIndex) {
		// case 0:
		// get_tabHost().setCurrentTabByTag("subject");
		// break;
		// case 1:
		// get_tabHost().setCurrentTabByTag("conversation");
		// break;
		// case 2:
		// get_tabHost().setCurrentTabByTag("userlist");
		// break;
		// }
		if(!NetworkController.getIsThanhLapNhom()){
			NetworkController.setStated(true);
			//t=new PingThread("Test");
			//t.start();
		}
	}

	// ============================

	public void Show(String message) {

		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).create();
		dlg.show();
	}

	public void ShowMessageKicked() {
		// Toast.makeText(this, "hehe Xin chao", Toast.LENGTH_SHORT).show();
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage("Bạn đã bị mời ra khỏi nhóm.")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						NetworkController.CloseDiscussActivity();
					}
				}).create();
		dlg.show();
	}

	public void HienThiMHBieuQuyetKick() {
		Log.d("Phu", "vao ham HienThiMHBieuQuyetKick");
		Intent i = new Intent(this.getBaseContext(), frmBieuQuyetMoiRoiNhom.class);
		startActivity(i);
	}

	public void ShowSetTimeStopTalking(final String ipStop) {
		final EditText txtTimeTalk = new EditText(this);
		txtTimeTalk.setSingleLine();
		txtTimeTalk.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian buộc ngừng thảo luận")
				.setMessage("Thời gian được tính bằng giây.").setView(txtTimeTalk)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String StrTime = txtTimeTalk.getText().toString();
						int time = Integer.parseInt(StrTime);
						timeStopTalk = time;
						ipBeingStopTalk = new Address(ipStop);
						NetworkController.GuiYeuCauNgungThaoLuan(ipBeingStopTalk, time);
						Log.d("Phu", "vao onclick ngung noi");
						long timeLong = timeStopTalk * 1000;
						Toast.makeText(getBaseContext(), timeLong + "", 1).show();
						CountDownTimer timer = new CountDownTimer(timeLong, 1000) {

							@Override
							public void onTick(long millisUntilFinished) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onFinish() {
								// TODO Auto-generated method stub
								
								NetworkController.GuiChoPhepThaoLuan(ipBeingStopTalk);
							}
						}.start();
					}

				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();
		dlg.show();
	}

	public void ShowSetTimeVoteKick(final String IP) {

		Log.d("Phu", " vao ShowSetTimeVoteKick");
		Log.d("Phu", "ip kick" + IP);
		Log.d("Phu", "My ip " + NetworkController._peer.getAddressPeer());
		String s[] = IP.split(":");

		String ipBeKick = s[1] + ":" + s[2];
		Log.d("Phu", "ip be kick " + ipBeKick);
		if (NetworkController._peer.getAddressPeer().equals(ipBeKick)) {
			NetworkController.ShowMessageNoticeTAB("Bạn không thể làm điều này!");
		} else {
			final EditText txtTime = new EditText(this);
			txtTime.setSingleLine();
			txtTime.setInputType(2);
			AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian biểu quyết")
					.setMessage("Thời gian được tính bằng giây.").setView(txtTime)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							String StrTime = txtTime.getText().toString();
							int time = Integer.parseInt(StrTime);
							timeVoteKick = time;
							yesVote = new ArrayList<Integer>();
							noVote = new ArrayList<Integer>();
							ipBeingKick = new Address(IP);
							memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
							for (CMember member : memberList) {
								NetworkController.SendVoteKickMember(new Address(member.get_ip()), ipBeingKick, time);
							}
							Log.d("Phu", "Da gui xong kick");
							// dem thoi gian
							long kickTime = timeVoteKick * 1000;

							CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
								@Override
								public void onTick(long millisUntilFinished) {

								}

								@Override
								public void onFinish() {
									kickVoteResult = 0;
									if (yesVote.size() != 0 || noVote.size() != 0) {
										if (yesVote.size() >= noVote.size()) {
											kickVoteResult = 1;
										}
										for (CMember member : memberList) {
											Log.d("Phu", "gui toi " + member.get_ip());
											NetworkController.SendResultVoteKickMember(new Address(member.get_ip()),
													kickVoteResult, ipBeingKick);
										}
									} else {
										// NetworkController.ShowMessageNotice("Không có ai tham gia biểu quyết.");
										NetworkController.ShowMessageNoticeTAB("Không có ai tham gia biểu quyết.");
										NetworkController.SendResultVoteKickMember(new Address(ipBeingKick),
												kickVoteResult, ipBeingKick);
									}
								}
							}.start();
						}
					}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

						}
					}).create();
			dlg.show();
		}
	}

	// ======================

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		// menu.add(Menu.NONE, NOTEPAD, Menu.NONE, "Note")
		// .setIcon(R.drawable.img_clear)
		// .setAlphabeticShortcut('e');
		// menu.add(Menu.NONE, INTERACTION, Menu.NONE, "Cộng tác")
		// .setIcon(R.drawable.img_cauhoi)
		// .setAlphabeticShortcut('f');
		// menu.add(Menu.NONE, SETTING, Menu.NONE, "Tuỳ chỉnh")
		// .setIcon(R.drawable.img_chat)
		// .setAlphabeticShortcut('g');
		// return(super.onCreateOptionsMenu(menu));
		new MenuInflater(getApplication()).inflate(R.menu.omnu_thao_luan, menu);
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		// switch (item.getItemId()) {
		// case NOTEPAD:
		// startActivity(new Intent(this, FrmNote.class));
		// return(true);
		// case INTERACTION:
		// startActivity(new Intent(this, FrmInteraction.class));
		// return(true);
		// case SETTING:
		// startActivity(new Intent(this, PrefSetting.class));
		// return(true);
		// }

		// return super.onOptionsItemSelected(item);
		int id = item.getItemId();
		switch (id) {
		case R.id.mnuDanhSachThanhVien:
			Intent iDanhSachThanhVien = new Intent(getBaseContext(), frmDanhSachThanhVienActivity.class);
			startActivityForResult(iDanhSachThanhVien, CODE_KICK);
			break;
		case R.id.mnuChiaSeTaiLieu:
			Toast.makeText(getBaseContext(), "Chia sẻ tài liệu", 1).show();
			break;
		case R.id.mnuVaoTroCuaToi:
			Intent iVaiTro = new Intent(getBaseContext(), frmVaiTroCuaToiActivity.class);
			startActivity(iVaiTro);
			break;
		case R.id.mnuQuyenCuaToi:
			Intent iQuyen = new Intent(getBaseContext(), frmQuyenCuaToi.class);
			startActivity(iQuyen);
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d("Phu", "vao tabActivity  onstart");
		if (NetworkController._peer == null) {
			Log.d("Phu", "_peer == null");
			AccountDTO account = new AccountDTO();			
			account.set_Username("phu");
			NetworkController.init("MES", Protocol.PORT, account);
			NetworkController.resetRole();
			this.setTitle(NetworkController._peer.getAddressPeer());
		}
		if (NetworkController.getIsThanhLapNhom()) {
			Log.d("Phu", "Là người thành lập nhóm");
			ArrayList<Quyen> ruleList = ReadWriteFileController.readRule(getApplicationContext(),
					ReadWriteFileController.RULE_BASE_PATH);
			RoleDTO role = new RoleDTO("Người sáng lập nhóm", ruleList);
			NetworkController._peer.account.resetRole();
			NetworkController._peer.account.addRole(role);
			for(Quyen q : ruleList){
				Log.d("Phu", "rule:  "+q.getName());
			}
		} else {
			Log.d("Phu", "Là người thành viên!");
			boolean rs = NetworkController.resetRole();
			if (!rs) {
				Show("Không tồn tại file: " + ReadWriteFileController.MY_ROLE_PATH);
			}

		}

		this.setTitle(NetworkController._peer.getAddressPeer());

	}

	public static void set_tabHost(TabHost _tabHost) {
		tabActivity._tabHost = _tabHost;
	}

	public static TabHost get_tabHost() {
		return _tabHost;
	}

	public static void setTabIndex(int tabIndex) {
		_tabIndex = tabIndex;
	}

	public static int getTabIndex() {
		return _tabIndex;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("Phu", " vao ham onActivityResult tab");
		Log.d("Phu", "resultCode= " + resultCode);
		if (resultCode == CODE_KICK) {
			Log.d("Phu", " CODE_KICK");
			String ipKick = data.getStringExtra(IP_RESULT);
			if (ipKick != null) {
				// userNameKick = data.getStringExtra(USERNAME_BEING_KICK);
				ShowSetTimeVoteKick(ipKick);

			}
		}
		// if (resultCode == CODE_CHATPEER) {
		// Log.d("Phu"," CODE_CHATPEER");
		// String ipFriend = data.getStringExtra(IP_CHATPEER);
		// if (ipFriend != null) {
		// NetworkController.ShowChatPeerNonParamater();
		// }
		// }
		if (resultCode == CODE_STOP_TALK) {
			Log.d("Phu", " CODE_STOP_TALK");
			String ipStop = data.getStringExtra(IP_RESULT);
			if (ipStop != null) {
				// userNameStop = data.getStringExtra(USERNAME_STOP_TALK);
				ShowSetTimeStopTalking(ipStop);
			}
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		Log.d("Phu","tabActivity onStop");
		frmTreeNodeActivity.isActive=false;
	}
	@Override
	public void onPause() {
		super.onPause();
		frmTreeNodeActivity.isActive=false;
		Log.d("Phu","tabActivity onPause");
	}
	@Override
	public void onDestroy(){
		super.onDestroy();
		PingThread.setRunning(false);
	}
}